<?php
/**
* @software         [JiJinCMS]
* @author           [上海集锦信息科技有限公司]
* @website          [http://www.jijinweb.com]
* @email            [sunny@jijinweb.com]
**/
namespace app\admin\controller;
use app\admin\model\NodeModel;
use think\facade\View;
use think\facade\Db;
use think\facade\Request;
class Role extends \app\admin\controller\Admin{
    public function initialize() { parent:: initialize();
        
        $this->model=new \app\admin\model\RoleModel();
        $this->validate=new \app\admin\validate\RoleValidate();
    }    
    public function index(){
        $data=$this->model->order('id desc')->select();
        View::assign("data",$data);
        return View::fetch();
    }
    //是否可管理所有栏目
    public function setAll_info(){
        $id=Request::param('id',0,"intval");
        $status=Request::param('status',0,"intval");
        $this->model->update(['id'=>$id,'all_info'=>$status]);
        //记录日志
        $this->UserLogModel->add("update",$this->model->getName(),$id,"是否可管理所有栏目");          
        $this->success("设置成功");
    }      
    //设置状态是否启用
    public function setStatus(){
        $id=Request::param('id',0,"intval");
        $status=Request::param('status',0,"intval");
        $this->model->update(['id'=>$id,'status'=>$status]);
        //记录日志
        $this->UserLogModel->add("update",$this->model->getName(),$id,"设置角色是否可见");          
        $this->success("设置成功");
    }    
    public function add(){
        if(request()->isPost()){
            $data=$this->request->param();
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }              
            $this->model->save($data);
            $lastId=$this->model->id;
            $this->UserLogModel->add("add",$this->model->getName(),$lastId,$this->request->param());
            $this->success("添加成功");
        }else{
            return View::fetch();
        }        
    }    
    public function update(){
        if(request()->isPost()){
            //获取数据并验证
            $data=$this->request->param();
            if(!$this->validate->check($data)){
                $this->error($this->validate->getError());
            }  
            //数据更新
            $data['status']=isset($data['status'])?1:0;
            $data['all_info']=isset($data['all_info'])?1:0;
            $this->model->update($data);
            //记录日志
            $this->UserLogModel->add("update",$this->model->getName(),$data["id"],$this->request->param());
            $this->success("修改成功");  
        }else{
            $id=Request::param('id');
            $r=$this->model->find($id);
            View::assign("r",$r);
            return View::fetch();
        }        
    }
    //删除
    public function delete(){
        $id=Request::param('id');
        if($this->model::destroy($id)){
            $this->UserLogModel->add("delete",$this->model->getName(),$id,$this->request->param());
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }
    //配置权限
    public function access(){
        if(request()->isPost()){
            $role_id=Request::param('role_id');
            if(!$role_id){
                $this->error("缺少参数");
            }
            //清空原权限
            Db::name("access")->where(array("role_id"=>$role_id))->delete();
            //重新组装权限
            $data=array();
            $access=Request::param('access');
            if(!$access){$this->error("请勾选权限！");}
            if($access){
                foreach($access as $v){
                    $tmp=explode("_",$v);
                    $data[]=array(
                        "role_id"=>$role_id,
                        "node_id"=>$tmp[0],
                        "level"=>$tmp[1],
                    );
                }  
                if(Db::name("access")->insertAll($data)){
                    $this->UserLogModel->add("update",$this->model->getName(),$role_id,"更新操作权限");
                    $this->success("操作成功",url("role/index"));
                }
            }
        }else{
            $role_id=Request::param('role_id');
            View::assign("role_id",$role_id);
            $r=$this->model->find($role_id);
            $data=Db::name("node")->order('sort asc')->select();
            //原有权限
            $access=Db::name("access")->where(array("role_id"=>$role_id))->where('level','<>',1)->column("node_id");
            //检查选中权限
            $access = $this->checked($access);
            $data=$this->node_merge($data,$access); 
            View::assign("data",$data);
            return View::fetch();
        }               
    }
    //数据合并
    private function node_merge($node,$access=null,$pid=0){
        $arr=array();
        foreach($node as $v){
            $v['field']="access[]";
            $id=$v['id'];
            $v['id']=$v['id']."_".$v['level'];
            $v['spread']=$v['level']<2;//默认让tree展开到二级
            if(is_array($access)){
                $v['checked']=in_array($v['id'],$access);
            }
            if($pid==$v['pid']){
                $v['children']=$this->node_merge($node,$access,$id);
                $arr[]=$v;
            }
        }
        return $arr;
    }
    //栏目权限配置
    public function access_cat(){
        if(request()->isPost()){
            $role_id=Request::param("role_id",0,"int");
            if(!$role_id){
                $this->error("缺少参数");
            }
            //
            $info_checked=isset($_POST["info_checked"])?implode("|",$_POST["info_checked"]):"";
            if($info_checked){
                $info_checked="|".$info_checked."|";
            }
            $info_view=isset($_POST["info_view"])?implode("|",$_POST["info_view"]):"";
            if($info_view){
                $info_view="|".$info_view."|";
            }            
            $info_add= isset($_POST["info_add"])?implode("|",$_POST["info_add"]):"";
            if($info_add){
                $info_add="|".$info_add."|";
            }            
            $info_editor=isset($_POST["info_editor"])?implode("|",$_POST["info_editor"]):"";
            if($info_editor){
                $info_editor="|".$info_editor."|";
            }            
            $info_delete=isset($_POST["info_delete"])?implode("|",$_POST["info_delete"]):"";
            if($info_delete){
                $info_delete="|".$info_delete."|";
            }            
            $this->model->update(array(
                "id"=>$role_id,
                "info_checked"=>$info_checked,
                "info_view"=>$info_view,
                "info_add"=>$info_add,
                "info_editor"=>$info_editor,
                "info_delete"=>$info_delete,
            ));
            $this->UserLogModel->add("update",$this->model->getName(),$role_id,"更新栏目权限");
            $this->success("操作成功",url("index"));
        }else{
            $role_id=Request::param("role_id");
            View::assign("data",$this->forCat());
            View::assign("r",$this->model->find($role_id));
            return View::fetch();
        }               
    }
    //返回所有栏目的数组
    public function forCat($pid=0,$str=array()){
        $cat=Db::name("cat")->where("pid",$pid)->field("catid,level,name,modelid,status,sort,pid")->order("sort asc,catid desc")->select();    
        if(count($cat)>0){
            foreach($cat as $v){              
                $nbsp_str="";
                for($i=1;$i<$v['level'];$i++){
                    $nbsp_str.=" &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
                }
                $str1=array();
                $str1=$v;
                $str1["str"]=$nbsp_str." |-";
                $str[]=$str1;
                $str=$this->forCat($v['catid'],$str);
            }            
            return $str;
        }else{
            return $str;
        }
    }

    public function checked($access)
    {
        $arr = array();
        foreach ($access as $k=>$v){
            //查找他的所有子集
            $childs = NodeModel::where('pid',$v)->select();
            foreach ($childs as $v1){
                if(!in_array($v1['id'],$access)){
                    $access[$k] = 'no';
                    break;
                }
            }
        }
        foreach ($access as $v){
            if ($v != 'no'){
                $arr[] = $v;
            }
        }
        return $arr;
    }
}